import { _decorator, Component, Node, RigidBody, log, v3, Collider, game } from "cc";
const { ccclass, property } = _decorator;

@ccclass("Ball")
export class Ball extends Component {
	initSpeed = 0;

	onLoad() {
		let collider = this.getComponent(Collider);
		collider?.on("onCollisionEnter", this.onCollisionEnter, this);
	}

	start() {
		// [3]
	}

	update(){
		if(this.node.position.y<-10){
			game.emit('game-over');
		}
	}

	//向下加速
	boost() {
		let rigid = this.node.getComponent(RigidBody);
		if (this.initSpeed == 0) {
			rigid?.setLinearVelocity(v3(0, -4, 0));
		} else {
			rigid?.setLinearVelocity(v3(0, -this.initSpeed, 0));
		}
	}

	//反弹
	bounce() {
		let rigid = this.node.getComponent(RigidBody);
		if (!rigid) {
			return;
		}
		if (this.initSpeed == 0) {
			let ve = v3(0, 0, 0);
			rigid.getLinearVelocity(ve);
			this.initSpeed = ve.y;
		} else {
			rigid.setLinearVelocity(v3(0, this.initSpeed, 0));
		}
	}

	onCollisionEnter() {
		this.bounce();
		this.node.emit('collision')
	}
}
